package com.letianpai.activity.photoalbum;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.letianpai.R;
import com.letianpai.adapter.photoalbum.PictureNetwokAdapter;
import com.letianpai.adapter.photoalbum.PictureNetworkInfo;
import com.letianpai.common.client.CommonTool;
import com.letianpai.common.client.HttpFileUploadClient;
import com.letianpai.common.client.HttpUploadClient;
import com.letianpai.common.client.ModelResult;
import com.letianpai.common.component.loading.LoadingDialog;
import com.letianpai.common.server.ResultBean;
import com.letianpai.common.server.ServerInterface;
import com.letianpai.common.server.ServerTool;
import com.letianpai.common.tool.FileUtil;
import com.letianpai.common.tool.StringUtil;
import com.letianpai.db.entity.PictureInfo;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-9-26
 * Time: 上午9:31
 * 新建相册
 */
public class NewAlbumActivity extends Activity {

    private final static int CAMERA_BACK_CODE = 100000;
    private String file_name;
    private LoadingDialog loadingDialog;
    private BottomCameraPopupWindow bottomPopWin;//自定义
    private String username, roomId, albumId, owner;
    private GridView pictureGv;
    private PictureNetwokAdapter netwokAdapter;
    private RelativeLayout bottomRl;
    private TextView deletePictureTv;
    private List<PictureNetworkInfo> pictureList = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.new_album);
        pictureList = new ArrayList<PictureNetworkInfo>();
        TextView createTv = (TextView) findViewById(R.id.home_create_album_tv);
        RelativeLayout topRl = (RelativeLayout) findViewById(R.id.new_album_top_ll);

        TextView deleteTv = (TextView) findViewById(R.id.new_album_delete_tv);
        ImageButton backTv = (ImageButton) findViewById(R.id.top_back_ib);
        backTv.setOnClickListener(new BackOnClickListener());
        pictureGv = (GridView) findViewById(R.id.new_album_picture_gv);
        bottomRl = (RelativeLayout) findViewById(R.id.new_album_picture_bottom_rl);
        deletePictureTv = (TextView) findViewById(R.id.new_album_picture_delete_tv);
        deletePictureTv.setOnClickListener(new DeletePictureClickListener());
        createTv.setOnClickListener(new ShowPopWinClickListener());
        deleteTv.setOnClickListener(new DeleteOnClickListener());
        Intent intent = getIntent();
        roomId = intent.getStringExtra("roomid");
        username = intent.getStringExtra("username");
        albumId = intent.getStringExtra("albumId");
        owner = intent.getStringExtra("owner");
        if (!username.equals(owner)) {
            deleteTv.setVisibility(View.GONE);
            createTv.setVisibility(View.GONE);
        }
        new PictureTask(false).execute();
    }

    //删除 展示事件
    class DeleteOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (bottomRl.getVisibility() == View.VISIBLE) {
                bottomRl.setVisibility(View.GONE);
                new PictureTask(false).execute();

            } else {
                bottomRl.setVisibility(View.VISIBLE);
                new PictureTask(true).execute();
            }
        }
    }

    class BackOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            returnBack();
        }
    }

    class DeletePictureClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            String photoIdArray = "";
            for (PictureNetworkInfo info : pictureList) {
                if (info.isWhetherSelected()) {
                    photoIdArray = photoIdArray + info.getPhotoid() + ",";
                }
            }
            if (StringUtil.isNotBlank(photoIdArray)) {
                photoIdArray = photoIdArray.substring(0, photoIdArray.length() - 1);
            }
            Map<String, String> maps = new HashMap<String, String>();
            maps.put("action", "del");
            maps.put("roomid", roomId);
            maps.put("catid", albumId);
            maps.put("username", username);
            maps.put("photoid", photoIdArray);
            ServerTool.getInstance().methodPost(NewAlbumActivity.this, "roomPhotoServlet", maps, new DeletePictureRealize());
        }
    }

    class DeletePictureRealize implements ServerInterface {
        @Override
        public void gainData(ResultBean bean) {
            if (bean.isSuccess()) {
                new PictureTask(false).execute();
            } else {
                Toast.makeText(NewAlbumActivity.this, "服务忙，请您稍后再试", Toast.LENGTH_LONG).show();
            }
            bottomRl.setVisibility(View.GONE);
        }
    }

    class ShowPopWinClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            //实例化SelectPicPopupWindow
            bottomPopWin = new BottomCameraPopupWindow(NewAlbumActivity.this, new AlbumClickListener());
            //显示窗口
            bottomPopWin.showAtLocation(NewAlbumActivity.this.findViewById(R.id.home_create_album_tv), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        }
    }

    class AlbumClickListener implements View.OnClickListener {


        @Override
        public void onClick(View v) {
            bottomPopWin.dismiss();
            switch (v.getId()) {
                case R.id.new_album_local_album_tv: {
                    //本地相册
                    Intent intent = new Intent(NewAlbumActivity.this, LocalAlbumActivity.class);
                    intent.putExtra("roomid", roomId);
                    intent.putExtra("username", username);
                    intent.putExtra("albumId", albumId);
                    intent.putExtra("owner", owner);
                    startActivityForResult(intent, 19999);
                    break;
                }
                case R.id.new_album_camera_tv: {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    try {
                        //指定存放拍摄照片的位置
                        String imageFileName = UUID.randomUUID().toString().substring(0, 8) + ".jpg";
                        Uri uri = Uri.fromFile(new File(CommonTool.PROJECT_IMAGE_PATH, imageFileName));
                        file_name = CommonTool.PROJECT_IMAGE_PATH + File.separator + imageFileName;
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, false);
                        startActivityForResult(intent, CAMERA_BACK_CODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA_BACK_CODE) {
                new UploadTask().execute();
            }
            if (requestCode == 19999) {
                new PictureTask(false).execute();
            }


        }
    }


    class UploadTask extends AsyncTask<String, Integer, Boolean> {
        //https://github.com/feicien/StudyDemo/commit/0ee6f1aed07bfcd55d070474cb188833034d6c30
        UploadTask() {
            loadingDialog = new LoadingDialog(NewAlbumActivity.this);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog.show();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            FileUtil.galleryAddPic(NewAlbumActivity.this, file_name);
            List<PictureInfo> pictureList = new ArrayList<PictureInfo>();
            PictureInfo picture = new PictureInfo();
            picture.setPicType("jpg");
            picture.setPicPath(file_name);
            picture.setPicMd5(FileUtil.getFileMD5(new File(file_name)));
            pictureList.add(picture);
            if (pictureList.size() < 1) {
                return Boolean.valueOf(false);
            }
            Map<String, String> map = new HashMap<String, String>();
            map.put("roomid", roomId);
            map.put("action", "upload");
            map.put("catid", albumId);
            map.put("username", username);
            map.put("num", String.valueOf(pictureList.size()));
            ModelResult<String> model = HttpFileUploadClient.doVeryLongPost("roomPhotoServlet", map, pictureList);
            if (model.isReturnResult()) {
                return Boolean.valueOf(true);
            } else {
                return Boolean.valueOf(false);
            }
        }

        @Override
        protected void onPostExecute(Boolean res) {
            super.onPostExecute(res);
            loadingDialog.dismiss();
            if (res.booleanValue()) {
                //刷新本地
                Toast.makeText(NewAlbumActivity.this, "上传照片成功", Toast.LENGTH_LONG).show();
                new PictureTask(false).execute();
            } else {
                Toast.makeText(NewAlbumActivity.this, "服务忙，请您稍后再试", Toast.LENGTH_LONG).show();
            }
        }
    }

    class PictureTask extends AsyncTask<String, Integer, List<PictureNetworkInfo>> {
        boolean delete;

        PictureTask(boolean delete) {
            this.delete = delete;
            loadingDialog = new LoadingDialog(NewAlbumActivity.this);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog.show();
        }

        @Override
        protected void onPostExecute(List<PictureNetworkInfo> res) {
            super.onPostExecute(res);
            loadingDialog.dismiss();
            netwokAdapter = new PictureNetwokAdapter(NewAlbumActivity.this, delete, username, res);
            pictureGv.setAdapter(netwokAdapter);
        }

        @Override
        protected List<PictureNetworkInfo> doInBackground(String... params) {
            Map<String, String> mapParam = new HashMap<String, String>();
            mapParam.put("action", "get");
            mapParam.put("roomid", roomId);
            mapParam.put("catid", albumId);
            mapParam.put("username", username);
            mapParam.put("is_filter", "");
            pictureList = new ArrayList<PictureNetworkInfo>();
            ModelResult<PictureNetworkInfo> modelResult = HttpUploadClient.doPost("roomPhotoServlet", mapParam);
            if (modelResult.isReturnResult()) {
                try {
                    JSONObject parentObj = new JSONObject(modelResult.getContent());
                    String url = parentObj.getString("static_url");
                    JSONArray childArray = parentObj.getJSONArray("photo_list");

                    int count = childArray.length();
                    for (int i = 0; i < count; i++) {
                        PictureNetworkInfo picture = new PictureNetworkInfo();
                        JSONObject childObj = childArray.getJSONObject(i);
                        picture.setPhotoid(childObj.getString("photoid"));
                        picture.setPhotoUrl(url + childObj.getString("photo"));
                        picture.setOwner(childObj.getString("owner"));
                        picture.setAddtime(childObj.getString("addtime"));
                        //删除
                        if (delete) {
                            picture.setWhetherSelected(false);
                            if (username.equals(picture.getOwner())) {
                                pictureList.add(picture);
                            }
                        } else {
                            pictureList.add(picture);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return pictureList;
        }
    }

    @Override
    public void onBackPressed() {
        returnBack();
    }

    private void returnBack() {
        Intent intent = new Intent();
        intent.setAction("com.letianpai.album.action.broadcast");
        sendBroadcast(intent);
        finish();
    }

}
